package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.query.StrategyCatalogQuery;
import cn.wolfcode.luowowo.repository.DestinationRepository;
import cn.wolfcode.luowowo.repository.StrategyCatalogRepository;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.util.CatalogVO;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepository repository;
    @Autowired
    private DestinationRepository destinationRepository;
    @Override
    public StrategyCatalog get(String id) {
        Optional<StrategyCatalog> optional = repository.findById(id);
        //如果数据库不是空的
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Autowired
    private MongoTemplate template;
    /**
     * 分页操作
     * @param qo 分页条件
     * @return
     */
    @Override
    public Page list(StrategyCatalogQuery qo) {
        Query query = new Query();
        Page<StrategyCatalog> page = DBHelper.query(template, StrategyCatalog.class, query, qo.getPageable());
        return page;
    }

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        Optional<Destination> byId = destinationRepository.findById(strategyCatalog.getDestId());
        strategyCatalog.setDestName(byId.get().getName());
        if (!StringUtils.hasLength(strategyCatalog.getId())){
            strategyCatalog.setId(null);
            repository.save(strategyCatalog);
        }else{
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(strategyCatalog.getId()));
            DBHelper.update(template,query,strategyCatalog,"destId","destName","state","name","sequence","strategies");
        }
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot);
        template.updateMulti(query,update,StrategyCatalog.class);
    }

    @Override
    public List<CatalogVO> groupList() {
        List<CatalogVO> list = new ArrayList<>();
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg,Map.class);
        List<Map> datas = result.getMappedResults();
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();
            vo.setDestName(data.get("_id").toString());
            List<Map<String, Object>> mm = new ArrayList<>();
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            for (int i = 0;i < names.size(); i++) {
                Map<String, Object> vv = new HashMap<>();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                mm.add(vv);
            }
            vo.setMapList(mm);
            list.add(vo);
        }
        System.out.println(list);
        return list;
    }

    @Autowired
    private StrategyRepository strategyRepository;
    @Override
    public List<StrategyCatalog> findByDestId(String id) {
        Query query = new Query();
        //由目的地id查所有的攻略分类
        query.addCriteria(Criteria.where("destId").is(id));
        List<StrategyCatalog> strategyCatalogs = template.find(query, StrategyCatalog.class);
        for (StrategyCatalog strategyCatalog : strategyCatalogs) {
            //攻略分类id查所有的攻略明细
            List<Strategy> byCatalogId = strategyRepository.findByCatalogId(strategyCatalog.getId());
            //把明细设置进分类中
            strategyCatalog.setStrategies(byCatalogId);
        }
        return strategyCatalogs;
    }
}
